#ifndef DEALDATE_H
#define DEALDATE_H

#include <QThread>
#include <QTcpSocket>
#include <QHostAddress>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include "date.h"

class WorkerThread : public QThread {
    Q_OBJECT
    QTcpSocket *socket;
    QList<ParkingDate*> m_parkingSpots;

public:
    explicit WorkerThread(QObject *parent = nullptr) : QThread(parent) {}

protected:
    void run() override {
        // 创建QTcpSocket实例
        QTcpSocket *socket = new QTcpSocket(this);

        // 连接信号和槽以处理网络事件
        connect(socket, &QTcpSocket::connected, this, &WorkerThread::onConnected);
        connect(socket, &QTcpSocket::readyRead, this, &WorkerThread::onReadyRead);
        connect(socket, &QTcpSocket::disconnected, this, &WorkerThread::onDisconnected);
        connect(socket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), this, &WorkerThread::socketError);

        // 连接到服务器
        socket->connectToHost(QHostAddress("192.168.1.112"), 10000); // 使用实际的服务器地址和端口

        // 开始网络事件循环
        exec();
    }

signals:
    void finished();
    void dataReceived(const QByteArray&);

private slots:
    void onConnected() {
        // 连接成功时的处理逻辑
        qDebug() << "Connected to server.";
    }

    void onDisconnected() {
        // 连接断开时的处理逻辑
        qDebug() << "Disconnected from server.";
    }

    void socketError(QAbstractSocket::SocketError error) {
        // 处理网络错误
        qDebug() << "Socket error:" << error;
    }

    void onReadyRead() {
           // 当有数据可读时的处理逻辑
           QByteArray data = socket->readAll();
           // 将QByteArray转换为QString
           QString strData = QString::fromUtf8(data);

           // 使用QJsonDocument::fromJson()解析JSON数据
           QJsonDocument doc = QJsonDocument::fromJson(data);
           if (doc.isObject()) {
               QJsonObject obj = doc.object();
               // 处理JSON对象，例如：
               bool isOccupied = obj["occupied"].toBool();
               QString spotId = obj["spot_id"].toString();
               // 根据JSON数据更新ParkingDate对象的状态
               for (const auto& spot : m_parkingSpots) {
                   if (spot->getSpotId() == spotId) {
                       spot->setOccupied(isOccupied);
                       // 更新界面或其他逻辑
                       break;
                   }
               }
           }

           // 发射信号，通知主界面数据已接收
           emit dataReceived(data);
       }
};

#endif // DEALDATE_H
